#include <pthread.h>
#include <memory>
#include <vector>
#include <iostream>
#include <unistd.h>
using namespace std;

/*
    使用锁来保证线程安全
    模拟抢票的行为
*/

int tickets = 10000;
// 全局变量/静态变量锁，定义时初始化，不需要进行 destory
// pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex;


void* RobTickets(void* args)
{
    string name = *static_cast<string*>(args);
   
    while(true)
    {
        usleep(1); // 模拟抢票行为
        pthread_mutex_lock(&mutex);
        if(tickets > 0)
            tickets--;
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
        pthread_mutex_unlock(&mutex);
    }
    cout << name << "完成了抢票 " << tickets << endl;
    
    return nullptr;
}

int main()
{
    int num = 4;
    pthread_t tids[4];
    vector<shared_ptr<string>> vsp(num);
    // 进行init初始化，需要destroy
    pthread_mutex_init(&mutex,nullptr);
    for(int i = 0; i < 4; i++)
    {
        char buf[32];
        snprintf(buf,sizeof(buf),"线程-%d",i);   
        vsp.emplace_back(new string(buf));
        pthread_create(tids+i,nullptr,RobTickets,vsp.back().get());
    }
    for(int i = 0; i < 4; i++)
    {
        pthread_join(tids[i],nullptr);
    }
    pthread_mutex_destroy(&mutex);
    
    return 0;
}